package com.xjh.him.controller;

import com.xjh.him.annotation.LoginVerify;
import com.xjh.him.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.xjh.tool.Checks;
import org.xjh.tool.common.ErrorMsg;
import org.xjh.tool.vo.AjaxResultVO;

import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/image")
public class FileController {

    @Value("${server.target-address}")
    private String serverAddress;

    @Value("${server.port}")
    private int serverPort;

    @LoginVerify
    @RequestMapping("/upload")
    public AjaxResultVO upload(MultipartFile file) {
        String originName = file.getOriginalFilename();
        if (Checks.isEmpty(originName)) {
            return AjaxResultVO.getFailureResult("上传文件名不能为空");
        }
        String suffixName = originName.substring(originName.lastIndexOf('.'));
        String fileName = FileUtil.generateFileName(suffixName);
        String path = FileUtil.IMAGE_BASE_PATH + fileName;
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            log.error("upload err, ", e);
            return AjaxResultVO.getFailureResult(ErrorMsg.ERR_SYSTEM_BUSY);
        }
        return AjaxResultVO.getSuccessResult(getFileUrl(fileName, FileUtil.TYPE_IMAGE));
    }

    private String getFileUrl(String filename, String type) {
        return String.format("http://%s:%d/%s/%s", serverAddress, serverPort,
                type, filename);
    }
}
